<?php

namespace ary;

use Psr\Http\Message\ResponseInterface;
use ShidianUtil\Api\HttpResponse;
use ShidianUtil\Api\HttpResponseTrait;
use think\exception\ValidateException;

/**
 * 案如云接口响应
 * Class AryResponse
 * @package ary
 */
final class AryResponse implements HttpResponse
{
    use HttpResponseTrait;

    private $success;
    private $decode_contents;

    public function __construct(ResponseInterface $response, bool $success, array $decode_contents = [])
    {
        $this->response = $response;
        $this->success = $success;
        $this->decode_contents = $decode_contents;
    }

    /**
     * 三方接口响应结果是否成功
     * @return bool
     */
    public function isSuccess(): bool
    {
        return $this->success;
    }

    /**
     * 获取响应体中已解析的数据
     * @return array
     */
    public function getDecodeContents(): array
    {
        return $this->decode_contents;
    }

    /**
     * 获取解析后的内容，如果请求结果不是成功，就报错
     * @param string $message 默认保存信息
     * @param bool $cover 是否强制覆盖报错信息
     * @return array
     */
    public function getDecodeContentsOrThrow(string $message, bool $cover = false): array
    {

        $decodeContents = $this->getDecodeContents();
        if (!$this->isSuccess()) {
            if (!$cover && $decodeContents && is_array($decodeContents) && not_blank($decodeContents['msg'] ?? null)) {
                $message = $decodeContents['msg'];
            }
            throw new ValidateException($message);
        }
        return $decodeContents;
    }
}
